package com.sth.es;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @Author: sitianhong
 * @Description: 创建索引
 * @Since: create in 2021/6/14 0014 13:29
 */
public class Esdemo5_Doc_Insert {
    public static void main(String[] args) throws IOException {
        // 创建es客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200)));
        // 新增文档 - 请求对象
        IndexRequest request = new IndexRequest();
// 设置索引及唯一性标识
        request.index("user").id("1001");
// 创建数据对象
        EsDemo4_User user = new EsDemo4_User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");
        ObjectMapper objectMapper = new ObjectMapper();
        String productJson = objectMapper.writeValueAsString(user);
// 添加文档数据，数据格式为JSON格式
        request.source(productJson, XContentType.JSON);
// 客户端发送请求，获取响应对象
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
////3.打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());
        // 关闭ES客户端
        esClient.close();
    }
}
